package com.gitee.cui.netty.echoServer;

import com.gitee.cui.util.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;

/**
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/22 16:30
 **/
@ChannelHandler.Sharable
public class NettyEchoClientHandler extends ChannelInboundHandlerAdapter {

    public static final NettyEchoClientHandler INSTANCE = new NettyEchoClientHandler();

    private NettyEchoClientHandler() {}

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 读取服务端发送过来的数据
        ByteBuf in = (ByteBuf) msg;
        int length = in.readableBytes();
        byte[] array = new byte[length];
        in.getBytes(in.readerIndex(), array);
        Logger.info("client received: " + new String(array, StandardCharsets.UTF_8));
        // 释放ByteBuf的两种方法
        // 1、手动释放ByteBuf
        in.release();
        // 2、调用父类的入站方法，将msg向后传递
        // super.channelRead(ctx, msg);
    }
}
